import { _decorator, Animation, AudioClip, AudioSource, CircleCollider2D, Component, director, Label, math, Node, RigidBody, RigidBody2D, v3, Vec3 } from 'cc';
import { Bird } from './Bird';
import { GameData } from './commons/GameData';
import { BirdHeadDirection, GameState } from './commons/GameConst';
import { GameEvent, GameLocalStorageKey } from './commons/GameEvent';
import { GameOverView } from './Views/GameOverView';
import { GameReadyView } from './Views/GameReadyView';
const { ccclass, property } = _decorator;

const BalanceValue = 3.8;

@ccclass('GameManager')
export class GameManager extends Component {

    @property(Node)
    bgNode: Node = null;

    @property(Node)
    landNode: Node = null;

    @property(Node)
    pipeNode: Node = null;

    @property(Node)
    birdNode: Node = null;

    @property(Node)
    gameOverNode: Node = null;

    private gameOverCom: GameOverView = null;

    @property(Node)
    gameReadyNode: Node = null;

    private gameReadyCom: GameReadyView = null;

    @property(Label)
    scoreLabel: Label = null;

    @property(AudioSource)
    getScoreSource: AudioSource = null;

    private birdComp: Bird = null;
    private birdRigidBody: RigidBody2D = null;

    protected onLoad(): void {
        if(this.birdNode){
            const birdComp = this.birdNode.getComponent(Bird);

            if(birdComp){
                this.birdComp = birdComp;
            }

            const birdRigidBody = this.birdNode.getComponent(RigidBody2D);
            if(birdRigidBody){
                birdRigidBody.sleep();
                birdRigidBody.enabled = false;
                birdRigidBody.enabled
                this.birdRigidBody = birdRigidBody;
            }
        }

        if(this.gameOverNode){
            const OverComp = this.gameOverNode.getComponent(GameOverView);

            if(OverComp){
                this.gameOverCom = OverComp;
                OverComp.hide();
            }   
        }

        if(this.gameReadyNode){
            const ReadyComp = this.gameReadyNode.getComponent(GameReadyView);

            if(ReadyComp){
                this.gameReadyCom = ReadyComp;
                ReadyComp.show();
            }
        }

        if(this.pipeNode){
            this.pipeNode.children.forEach(pipe => {
                if(pipe){
                    pipe.active = false;
                }
            })
        }
    }

    start() {
        this.initEvent();
        this.initUIData();
    }

    private restGameUI(){
        //重置水管
        if(this.pipeNode){
            let resetX = 700;
            this.pipeNode.children.forEach(pipe => {
                if(pipe){
                    pipe.active = false;
                    let posY = math.randomRange(470, 715);
                    resetX += 200;
                    pipe.setPosition(resetX, posY);
                }
            })
        }

        if(this.birdNode){
            this.birdNode.angle = 0;
            this.birdNode.setPosition(Vec3.ZERO);
            this.birdComp.setBirdHeadDirect(BirdHeadDirection.BH_Middle);
            this.birdComp.Play();
        }

        this.scoreLabel.string = `${"0"}`;

    }

    private initEvent(){
        this.node.on(Node.EventType.TOUCH_END,this.onTouchEndEvent,this);
        director.on(GameEvent.GAME_EVENT_START ,this.onGameStartEvent,this);
        director.on(GameEvent.GAME_EVENT_END ,this.onGameOverEvent,this);
        director.on(GameEvent.GAME_EVENT_RESTART ,this.onGameRestEvent,this);
        director.on(GameEvent.GAME_EVENT_UPDATE_SCORE,this.onUpdateScoreEvent,this);
    }

    private initUIData(){
        GameData.instance.curGameState = GameState.GS_GameReady;
    }

    updateMove(deltaTime: number) {
        this.updateBackground(deltaTime);
        this.updateLand(deltaTime);
        this.updatePipe(deltaTime);
    }


    private updateBackground(deltaTime: number) {
        //没有背景节点
        if(!this.bgNode){
            return;
        }

        let bgList = this.bgNode.children;
        for(let i = 0; i < bgList.length; i++){
            const bg = bgList[i];
            if(!bg){
                continue;
            }
            bg.setPosition(bg.position.x - 125 * deltaTime, bg.position.y);
            if(bg.position.x <= -720){
                bg.setPosition(720, bg.position.y);
            }
        }
    }

    private updateLand(deltaTime: number) {
        if(!this.landNode){
            return;
        }

        let landList = this.landNode.children;
        for(let i = 0; i < landList.length; i++){
            const land = landList[i];
            if(!land){
                continue;
            }
            land.setPosition(land.position.x - 125 * deltaTime, land.position.y);
            if(land.position.x <= -720){
                land.setPosition(720, land.position.y);
            }
        }
    }

    private updatePipe(deltaTime: number) {
        if(!this.pipeNode){
            return;
        }

        let pipeList = this.pipeNode.children;
        for(let i = 0; i < pipeList.length; i++){
            const pipe = pipeList[i];
            if(!pipe){
                continue;
            }
            pipe.active = true;
            pipe.setPosition(pipe.position.x - 125 * deltaTime, pipe.position.y);
            if(pipe.position.x <= -30){
                let posY = math.randomRange(470, 715);
                pipe.setPosition(970, posY);
            }
        }
    }

    private onTouchEndEvent(event:TouchEvent){
        
        if(this.birdNode && GameState.GS_GamePlaying == GameData.instance.curGameState){
            let posY = this.birdNode.position.y + 20;
            this.birdNode.setPosition(0, posY);
            this.birdComp.setBirdHeadDirect(BirdHeadDirection.BH_Middle);
            this.birdComp.playWingSource();

            this.birdRigidBody.sleep();
        }
    }

    update(deltaTime: number) {

        if(GameState.GS_GamePlaying != GameData.instance.curGameState){
            return;
        }

        this.updateMove(deltaTime);

        if(this.birdRigidBody){
            if(this.birdRigidBody.enabled == false){
           
                this.birdRigidBody.enabled = true;
            }   
    
            this.birdRigidBody.wakeUp();
        }
    }

    protected onDestroy(): void {
        this.node.off(Node.EventType.TOUCH_END,this.onTouchEndEvent,this);
        director.off(GameEvent.GAME_EVENT_END,this.onGameOverEvent,this);
        director.off(GameEvent.GAME_EVENT_RESTART ,this.onGameRestEvent,this);
        director.off(GameEvent.GAME_EVENT_UPDATE_SCORE,this.onUpdateScoreEvent,this);
    }

    onGameStartEvent(data:any){
        GameData.instance.curGameState = GameState.GS_GamePlaying;  // 状态设置为开始游戏
    }

    onGameOverEvent(data:any){
        if(this.birdComp){
            this.birdComp.setBirdHeadDirect(BirdHeadDirection.BH_Down);
            this.birdComp.stopPlay();
            this.birdComp.playDieSouce();
        }

        GameData.instance.curGameState = GameState.GS_GameOver;

        if(GameData.instance.curScore > GameData.instance.bestScore){
            GameData.instance.bestScore = GameData.instance.curScore;
        }

        this.scheduleOnce(()=>{

            this.gameOverCom.onUpdateShowGameOverInfo();
            this.gameOverCom.show();

            this.gameReadyCom.hide();
        },2);
    }

    onGameRestEvent(data:any){

        //游戏重新开始
        this.restGameUI();

        GameData.instance.curGameState = GameState.GS_GamePlaying;
    }

    onUpdateScoreEvent(data:any){
        this.getScoreSource.play();
        this.scoreLabel.string = `${GameData.instance.curScore.toString()}`;
    }
}


